package com.heima.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.service.FreemarkerService;
import com.heima.common.exception.CustomException;
import com.heima.file.service.impl.MinIOTemplate;
import com.heima.model.article.dtos.ArticleDto;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.search.pojos.SearchArticleVo;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.UUID;

/**
 * @author xiaquanen
 * @version 1.0
 * @project heima-leadnews
 * @date 2024/7/25 14:35:48
 */
@Service
public class FreemarkerServiceImpl implements FreemarkerService {

    @Autowired
    private Configuration configuration;

    @Autowired
    private MinIOTemplate minIOTemplate;

    @Autowired
    private ApArticleMapper apArticleMapper;

    @Autowired
    private KafkaTemplate<String,String> kafkaTemplate;

    /**
     * 创建文章模版，并存入数据库中
     *
     * @param articleDto
     */
    @Override
    @Async
    public void createFreemarker(ArticleDto articleDto) {
            try {
                //拿到模版
                Template template = configuration.getTemplate("article.ftl");
                //将数据和模版进行拼接
                HashMap<String, Object> hashMap = new HashMap<>();
                hashMap.put("content", JSONObject.parseArray(articleDto.getContent()));
                //输出
                StringWriter stringWriter = new StringWriter();
                template.process(hashMap, stringWriter);
                //生成文件名称
                InputStream is = new ByteArrayInputStream(stringWriter.toString().getBytes());
                String url = minIOTemplate.uploadHtmlFile("", articleDto.getId()+".html", is);
                is.close();
                ApArticle apArticle = new ApArticle();
                apArticle.setId(articleDto.getId());
                apArticle.setStaticUrl(url);
                articleDto.setStaticUrl(url);
                apArticleMapper.updateById(apArticle);

                //调用kafka将消息异步上架到es索引库中去
                SearchArticleVo searchArticleVo = new SearchArticleVo();
                BeanUtils.copyProperties(articleDto,searchArticleVo);
                kafkaTemplate.send("topic_add_es_article", JSON.toJSONString(searchArticleVo));
            }catch (Exception e)
            {
                e.printStackTrace();
                throw new CustomException(AppHttpCodeEnum.CREATE_ERROR_STATIC);
            }
    }
}
